package top.blackr.folivora.common.log.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.utils.StringUtil;
import org.slf4j.MDC;
import org.springframework.web.filter.CommonsRequestLoggingFilter;
import top.blackr.folivora.common.core.constants.CommonConstants;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

/**
 * MDC日志链路拦截器
 */
public class LogCommonsRequestLoggingFilter extends CommonsRequestLoggingFilter {

    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP1 = "127.0.0.1";

    private final static Set<String> URLS;

    static {
        URLS = new HashSet<>();
        URLS.add("/webjars");
        URLS.add("/swagger");
        URLS.add("/api-docs");
        URLS.add("/apple-touch-icon-precomposed");
        URLS.add("/favicon");
        URLS.add("/apple-touch-icon");
    }


    @Override
    protected boolean shouldLog(HttpServletRequest request) {
        return true;
    }

    @Override
    protected void beforeRequest(HttpServletRequest request, String message) {
        MDC.put(CommonConstants.TRACE_ID, StringUtil.getUUID());
    }

    @Override
    protected void afterRequest(HttpServletRequest request, String message) {
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/")) {
            return;
        }
        for (String url : URLS) {
            if (requestURI.contains(url)) {
                return;
            }
        }
        String uuid = MDC.get(CommonConstants.TRACE_ID);
        logger.info(STR."【\{uuid}】:【\{StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : "未登陆"}】【\{getIp(request)}】\{message}");
        MDC.remove(CommonConstants.TRACE_ID);
    }

    /**
     * 获取IP公网地址
     * <p>
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */
    public static String getIp(HttpServletRequest request) {
        String ip;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
            ip = request.getHeader("X-Original-Forwarded-For");
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Forwarded-For");
            }
            //获取nginx等代理的ip
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("x-forwarded-for");
            }
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if ($.isEmpty(ip) || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            // 兼容k8s集群获取ip
            if ($.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                    // 根据网卡取本机配置的IP
                    InetAddress iNet;
                    try {
                        iNet = InetAddress.getLocalHost();
                        ip = iNet.getHostAddress();
                    } catch (UnknownHostException e) {
                        ip = request.getRemoteAddr();
                    }
                }
            }
        } catch (Exception e) {
            ip = request.getRemoteAddr();
        }
        // 使用代理，则获取第一个IP地址
        if (!$.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }
        return ip;
    }
}
